import LayerController from './LayerController'

export default class CanvasController {
  /**
   * 定义画布类，控制画布内元素的增删改
   */
  constructor () {
    /**
     * 存放图层信息 layers: LayerController[]
     */
    this.layers = []
    /**
     * 存放当前激活的图层ID
     */
    this.activeId = null
    /**
     * 存放画布宽高
     */
    this.width = 0
    this.height = 0
    this.backgroundUrl = ''
  }
  /**
   * 初始化画布尺寸
   * @param {number} width 画布高度（px）
   * @param {number} height 画布宽度（px）
   */
  initCanvasSize (width, height) {
    this.width = width
    this.height = height
  }
  /**
   * 添加图层
   * @param {'text' | 'image'} type 图层类型
   * @param {string} content 图层内容（文本内容或图片地址）
   * @param {number | undefined} idx 插入图层的位置（可选参数）
   */
  addLayer (type, content, idx) {
    const newLayer = new LayerController(type, content, this.width, this.height)
    if (idx === undefined) {
      this.layers.push(newLayer)
    } else {
      this.layers.splice(idx, 0, newLayer)
    }
    return newLayer
  }
  /**
   * 激活图层
   * @param {number} layerId 需要激活的图层ID
   */
  activateLayer (layerId) {
    this.activeId = layerId
  }
  /**
   * 删除当前激活的图层
   */
  removeLayer () {
    const idx = this.layers.findIndex(function (layer) {
      return layer.id === this.activeId
    })[0]
    this.layers.splice(idx, 1)
    this.activeId = null
  }

  /**
   * 通过图层id查找图层
   * @param {string} id 图层id
   */
  findLayer (id) {
    const targetLayer = this.layers.filter(function (layer) {
      return layer.id === id
    })
    if (targetLayer.length === 1) {
      return targetLayer[0]
    } else {
      return null
    }
  }

  setLayerPosition (id, r) {
    const layer = this.findLayer(id)
    if (layer) {
      layer.setRect(r)
    }
  }

  // 设置background地址
  setBackgroundUrl (url) {
    this.backgroundUrl = url
  }
  setSize (width, height) {
    this.width = width
    this.height = height
  }
  toJSON () {
    return {
      layers: this.layers.map(function (layer) {
        return layer.toJSON()
      }),
      width: this.width,
      height: this.height,
      backgroundUrl: this.backgroundUrl
    }
  }

  fromJSON (obj) {
    const that = this
    const { width, height, layers, backgroundUrl } = obj
    if (this.width === 0 && this.height === 0) {
      this.width = width
      this.height = height
    }
    this.backgroundUrl = backgroundUrl
    that.layers = []
    layers.forEach(function (layer) {
      const newLayer = that.addLayer(new LayerController('text', '', that.width, that.height))
      newLayer.fromJSON(layer)
    })
  }
}
